package com.CST.websocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author qtx
 * @since 2023/5/15
 */
@Slf4j
@Component
@ServerEndpoint("/web_socket/{user}")
public class WebSocketServer {

    public static final ConcurrentHashMap<String, List<WebSocketClient>> webSocketClientMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功时触发，绑定参数
     *
     * @param session 与某个客户端的连接会话，需要通过它来给客户端发送数据
     * @param user    用户
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("user") String user) {
        log.info("user:{}", user);
        WebSocketClient client = new WebSocketClient();
        client.setSession(session);
        client.setUri(session.getRequestURI()
                .toString());

        List<WebSocketClient> webSocketClientList = webSocketClientMap.get(user);
        if (webSocketClientList == null) {
            webSocketClientList = new ArrayList<>();
        }
        webSocketClientList.add(client);
        webSocketClientMap.put(user, webSocketClientList);
    }

    /**
     * 连接关闭时触发，注意不能向客户端发送消息了
     *
     * @param user 用户
     */
    @OnClose
    public void onClose(@PathParam("user") String user) {
        log.info("onClose:{}", user);
        webSocketClientMap.remove(user);
    }

    /**
     * 通信发生错误时触发
     *
     * @param session 链接
     * @param error   错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     *
     * @param user    用户
     * @param message 消息
     */
    public static void sendMessage(String user, String message) {
        try {
            List<WebSocketClient> webSocketClientList = webSocketClientMap.get(user);
            if (webSocketClientList != null) {
                for (WebSocketClient webSocketServer : webSocketClientList) {
                    webSocketServer.getSession()
                            .getBasicRemote()
                            .sendText(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
